package code

import "go/ast"

type Function struct {
	Name     string
	Params   []Param
	Returns  []Type
	Comments []string
}
type Method struct {
	Function
	Receiver Receiver
}

type Receiver struct {
	Type Type
	Name string
}

func ExtractFunction(name string, commonts []string, funcType *ast.FuncType) *Function {
	funct := Function{
		Name:     name,
		Comments: commonts,
	}
	for _, param := range funcType.Params.List {
		paramType := getType(param.Type)

		if len(param.Names) == 0 {
			funct.Params = append(funct.Params, Param{Type: paramType})
			continue
		}

		for _, name := range param.Names {
			funct.Params = append(funct.Params, Param{
				Name: name.Name,
				Type: paramType,
			})
		}
	}

	if funcType.Results != nil {
		for _, result := range funcType.Results.List {
			funct.Returns = append(funct.Returns, getType(result.Type))
		}
	}
	return &funct
}

func ExtractMethod(funcDecl *ast.FuncDecl) *Method {
	name := funcDecl.Name.Name
	funcType := funcDecl.Type
	function := ExtractFunction(name, nil, funcType)

	recv := funcDecl.Recv
	if recv != nil && len(recv.List) > 0 {
		meth := Method{
			Function: *function,
			Receiver: Receiver{
				Type: getType(recv.List[0].Type),
				Name: recv.List[0].Names[0].Name,
			},
		}
		return &meth
	}

	return &Method{
		Function: *function,
	}
}
